<template>
  <p-card class="product-execu-semifinish" :bordered="false">
    <div class="table-page-search-wrapper">
      <!-- 半成品入库 -->
      <div class="product-execu-title">半成品入库</div>
      <p-form-model layout="inline" :model="inspectForm">
        <p-row :gutter="20">
          <p-col :xl="8" :md="8">
            <p-form-model-item label="送检单号">
              <p-input
                placeholder=""
                v-model="inspectForm.inStorageNo"
                readOnly
              ></p-input>
            </p-form-model-item>
          </p-col>
          <p-col :xl="8" :md="8">
            <p-form-model-item label="送检人员">
              <p-input
                readOnly
                placeholder=""
                v-model="$store.state.user.name"
              ></p-input>
            </p-form-model-item>
          </p-col>
          <p-col :xl="8" :md="8">
            <p-form-model-item label="送检时间" prop="storageOperatorTime">
              <p-input
                readOnly
                placeholder=""
                v-model="inspectForm.storageOperatorTime"
              ></p-input>
            </p-form-model-item>
          </p-col>
          <p-col :xl="8" :md="8">
            <p-form-model-item label="待检数量" prop="storageOperatorNum">
              <p-input
                readOnly
                placeholder=""
                v-model="inspectForm.storageOperatorNum"
              ></p-input>
            </p-form-model-item>
          </p-col>
          <p-col :xl="8" :md="8">
            <p-form-model-item label="管控方式">
              <p-input v-model="inspectForm.controlType" disabled />
            </p-form-model-item>
          </p-col>
          <p-col :xl="8" :md="8" v-show="selectBankList.length > 0">
            <p-form-model-item label="入库库位">
              <p-select
                v-if="selectBankList.length === 1"
                v-model="inspectForm.storageLocation"
                placeholder="请选择库位"
              >
                <p-select-option
                  v-for="item in storageLocations"
                  :value="item.storageno"
                  :key="item.storageno"
                  >{{ item.storagename }}</p-select-option
                >
              </p-select>
              <p style="color: red" v-else>不能同时选择不同库位</p>
            </p-form-model-item>
          </p-col>
        </p-row>
      </p-form-model>
      <!-- 送检范围条件 -->
      <div class="product-execu-title">送检范围条件</div>
      <p-form-model
        layout="inline"
        :model="form"
        :rules="rules"
        ref="rulesForm"
      >
        <p-row :gutter="24">
          <p-col :xl="8" :md="8">
            <p-form-model-item label="产品编码" prop="productCode">
              <p-select
                v-model="form.productCode"
                allowClear
                @change="changPro"
              >
                <p-select-option
                  v-for="item in Productcodes"
                  :value="item.productCode"
                  :key="item.productCode"
                  >{{ item.productCode }}</p-select-option
                >
              </p-select>
            </p-form-model-item>
          </p-col>
          <p-col :xl="8" :md="8">
            <p-form-model-item label="产品名称">
              <p-input
                placeholder=""
                v-model="form.productName"
                readOnly
              ></p-input>
            </p-form-model-item>
          </p-col>
          <p-col :xl="8" :md="8">
            <p-form-model-item label="PN实际送检数" prop="pnNum">
              <p-input
                placeholder=""
                v-model="form.pnNum"
                :disabled="inspectForm.controlType == 'SN'"
              ></p-input>
            </p-form-model-item>
          </p-col>
        </p-row>
        <p-row :gutter="24">
          <p-col :xl="8" :md="8">
            <p-form-model-item label="工序工单" class="product-stotage-list">
              <p-select
                mode="multiple"
                v-model="form.processBillNo"
                placeholder="Please select"
                @change="changeList"
              >
                <p-select-option
                  v-for="item in filteredOptionsGXGD"
                  :value="item.processBillNo"
                  :key="item.processBillNo"
                  >{{ item.processBillNo }}</p-select-option
                >
              </p-select>
            </p-form-model-item>
          </p-col>
          <p-col :xl="8" :md="8">
            <p-form-model-item label="生产工单" class="product-stotage-list">
              <p-select
                mode="multiple"
                v-model="form.productionNo"
                placeholder="Please select"
                @change="changeList"
              >
                <p-select-option
                  v-for="item in filteredOptionsSCGD"
                  :value="item.productionNo"
                  :key="item.productionNo"
                  >{{ item.productionNo }}</p-select-option
                >
              </p-select>
            </p-form-model-item>
          </p-col>
          <p-col :xl="8" :md="8">
            <p-form-model-item label="容器条码" class="product-stotage-list">
              <p-select
                mode="multiple"
                v-model="form.Containers"
                placeholder="Please select"
                @change="changeList"
              >
                <p-select-option
                  v-for="item in Containers"
                  :value="item"
                  :key="item"
                  >{{ item }}</p-select-option
                >
              </p-select>
            </p-form-model-item>
          </p-col>
        </p-row>
        <p-row :gutter="24">
          <p-col :xl="8" :md="8">
            <p-form-model-item label="入库库位" prop="">
              <p-select
                v-model="form.storageLocation"
                placeholder="请选择库位"
                @change="changeList"
              >
                <p-select-option
                  v-for="item in SCGDlist"
                  :value="item.storageLocation"
                  :key="item.storageLocation"
                  >{{ item.storageLocation }}</p-select-option
                >
              </p-select>
            </p-form-model-item>
          </p-col>
          <p-col :xl="8" :md="8">
            <p-form-model-item label="SN/PN">
              <p-input
                placeholder=""
                v-model.trim="form.pnsn"
                @change="changeList"
              ></p-input>
            </p-form-model-item>
          </p-col>
        </p-row>
      </p-form-model>
      <!-- 送检产品明细 -->
      <div class="product-execu-title">
        <div class="float-right">
          <p-button @click="back">取消</p-button>
          <p-button class="ml10" type="primary" @click="ProductForStorge"
            >送检</p-button
          >
        </div>
        送检产品明细
      </div>
      <p-table
        size="middle"
        bordered
        rowKey="wipId"
        :pagination="ipagination"
        :columns="columns"
        :dataSource="dataSource"
        :loading="loading"
        @change="handleTableChange"
        :rowSelection="{
          fixed: true,
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
        }"
      >
        <template slot="status" slot-scope="text">
          <p-tag v-if="text == 0" color="blue"
            ><p-icon type="clock-circle" />待检</p-tag
          >
          <p-tag v-else-if="text == 1" color="green"
            ><p-icon type="check-circle" />检验完成</p-tag
          >
        </template>
      </p-table>
    </div>
  </p-card>
</template>

<script>
import { api } from "@/api/manage";
import { filterObj, timestampToDatetime } from "@/utils/util";
import { postAction, getAction, putAction } from "@/api/manage";
import ReplaceModal from "./modules/ReplaceModal";
import mixins from "./modules/line-station";
const columns = [
  {
    title: "序号",
    dataIndex: "",
    key: "rowIndex",
    width: 60,
    align: "center",
    customRender: function (t, r, index) {
      return parseInt(index) + 1;
    },
  },
  {
    title: "线体 ",
    align: "center",
    dataIndex: "lineName",
  },
  {
    title: "生产工单",
    align: "center",
    dataIndex: "productionNo",
  },
  {
    title: "工序工单",
    align: "center",
    dataIndex: "processBillNo",
  },
  {
    title: "产品编码",
    align: "center",
    dataIndex: "productCode",
  },
  {
    title: "产品描述",
    align: "center",
    dataIndex: "productName",
  },
  {
    title: "栈容码/容器码",
    align: "center",
    dataIndex: "containerCode",
  },
  {
    title: "SN/PN",
    align: "center",
    dataIndex: "pnsn",
  },
  {
    title: "数量",
    align: "center",
    dataIndex: "pnsnQty",
  },
  {
    title: "库位",
    align: "center",
    dataIndex: "locationCode",
  },
  {
    title: "状态",
    align: "center",
    dataIndex: "checkStatus",
    scopedSlots: { customRender: "status" },
  },
];
export default {
  name: "",
  mixins: [mixins],
  components: {
    ReplaceModal,
  },
  data() {
    return {
      url: {
        list:
          "/mes-manufacture/mfHalfProductInStorage/getPnSnInfoForHalfProductForStorage", //送检产品列表
        getProductcode:
          "/mes-manufacture/mfHalfProductInStorage/getProductsForHalfProductSelect", //产品编码
        ProductForStorge:
          "/mes-manufacture/mfHalfProductInStorage/halfProductForStorage", //半成品入库
        getGXGD:
          "/mes-manufacture/mfHalfProductInStorage/getProcessInfoForHalfProduct", //根据产品编码获得工序工单
        getSCGD:
          "/mes-manufacture/mfHalfProductInStorage/getProductionInfoForHalfProduct", //通过产品编码获得生产工单
        getType:
          "/mes-manufacture/mfHalfProductInStorage/getControlTypeByProduct", //获得管控方式
        getContainer:
          "/mes-manufacture/mfHalfProductInStorage/getContainerCodeByProductCode", //根据产品编码获得容器
        updateLocationCode: "/mfWip/updateLocationCode", //修改库位
        getLocationCode: "/basic-business/auto/stStorage/all", //获得库位列表
      },
      columns: [],
      dataSource: [],
      ipagination: {
        current: 1,
        pageSize: 10,
        limit: 10,
        pageSizeOptions: ["10", "20", "30"],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条";
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      inspectForm: {
        inStorageNo: "", //入库单号
        storageOperatorName: "", //入库人员
        controlType: "", //PN
        storageOperatorNum: "",
        storageOperatorTime: "",
        storageLocation: "", //库位
      },
      form: {
        productCode: "", // 产品编码
        productName: "", // 产品名称
        processBillNo: [], //工序工单
        productionNo: [], //生产工单
        Containers: [],
        pnNum: "",
        pnsn: "",
      },
      selectedRowKeys: [],
      selectionRows: [],
      GXGDlist: [], //工序工单列表
      SCGDlist: [], //生产工单列表
      Containers: [], //容器列表
      Productcodes: [], //产品类别
      storageLocations: [], //库位列表
      selectBankList: [],
      loading: false,
      rules: {
        productCode: [
          { required: true, message: "请选择产品编码", trigger: "blur" },
        ],
        storageLocation: [
          { required: true, message: "请选择库位", trigger: "blur" },
        ],
        pnNum: [
          {
            pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/,
            message: "请输入数字",
          },
          {
            validator: (rule, value) => {
              return value < this.inspectForm.storageOperatorNum;
            },
            message: "实际送检数量不能大于待检数量",
          },
        ],
      },
    };
  },
  computed: {
    filteredOptionsGXGD() {
      return this.GXGDlist.filter(
        (o) => !this.form.processBillNo.includes(o.processBillNo)
      );
    },
    filteredOptionsSCGD() {
      return this.SCGDlist.filter(
        (o) => !this.form.productionNo.includes(o.productionNo)
      );
    },
  },
  created() {
    this.columns = columns;
    this.getRuleCodeValue();
    this.SNlist();
    this.getProductcode();
    // this.getGXGD();
    // this.getSCGD();
    // this.getContainer();
    // this.getLocationCode();
  },
  mounted() {
    this.getData();
  },
  methods: {
    timestampToDatetime,
    changeList() {
      this.SNlist();
    },
    getProductcode() {
      getAction(this.url.getProductcode, {}).then((res) => {
        if (res.success) {
          this.Productcodes = res.data;
        }
      });
    },
    getType() {
      postAction(this.url.getType, {
        productCode: this.form.productCode,
        factoryId: "H000",
      }).then((res) => {
        if (res.code === 0) {
          this.inspectForm.controlType = res.data || "SN";
        }
      });
    },
    //获得送检单号
    getRuleCodeValue() {
      let param = {
        rules: [
          { ruleCode: "mes_first_inspect_rule", columnName: "filedCode" },
        ],
      };
      putAction(api.ruleBaseURL, param).then((res) => {
        // 执行成功，获取返回的值，并赋到页面上
        if (res.success) {
          this.inspectForm.inStorageNo = res.data.filedCode;
        }
      });
    },
    //获得送检时间和送检人
    getData() {
      this.inspectForm.storageOperatorName = this.$store.state.user.name;
      this.inspectForm.storageOperatorTime = this.timestampToDatetime(
        new Date().getTime()
      );
    },
    //获得容器种类
    getContainer() {
      postAction(this.url.getContainer, {
        productCode: this.form.productCode,
      }).then((res) => {
        if (res.success) {
          this.Containers = res.data;
        } else {
          this.Containers = [];
        }
      });
    },
    //获得库位列表
    getLocationCode() {
      getAction(this.url.getLocationCode, {}).then((res) => {
        this.storageLocations = res.data;
      });
    },
    getGXGD() {
      postAction(this.url.getGXGD, { productCode: this.form.productCode }).then(
        (res) => {
          if (res.success) {
            this.GXGDlist = res.data;
          } else {
            this.GXGDlist = [];
          }
        }
      );
    },
    getSCGD() {
      postAction(this.url.getSCGD, { productCode: this.form.productCode }).then(
        (res) => {
          if (res.success) {
            this.SCGDlist = res.data;
          } else {
            this.SCGDlist = [];
          }
        }
      );
    },
    //更改库位
    updateLocationCode() {
      let pnsns = this.selectionRows.map((item) => {
        let { pnsn } = item;
        return pnsn;
      });
      const params = {
        locationCode: this.inspectForm.storageLocation,
        pnsns,
      };
      postAction(this.url.updateLocationCode, params).then((res) => {
        if (!res.success) {
          this.$message.error(res.msg);
        }
      });
    },
    //送检明细表
    SNlist() {
      let params = {
        controlType: 1 || this.inspectForm.controlType == "SN" ? 1 : 2,
        processBillNos: this.form.processBillNo,
        productionNos: this.form.productionNo,
        containerCodes: this.form.Containers,
        productCode: this.form.productCode,
        keyword: "",
        pnsn: this.form.pnsn,
        limit: this.ipagination.pageSize,
        pageNo: this.ipagination.current,
        locationCodes: this.form.storageLocation,
      };
      this.loading = true;
      postAction(this.url.list, params)
        .then((res) => {
          if (res.code === 0) {
            this.dataSource = res.data.records || [];
            this.inspectForm.storageOperatorNum = res.data.total;
            this.ipagination.total = res.data.total;
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
      this.selectBankList = Array.from(
        new Set(
          this.selectionRows.map((item) => {
            const { locationCode } = item;
            return locationCode;
          })
        )
      );
      console.log(this.selectBankList, this.selectionRows);
      this.inspectForm.storageLocation = this.selectBankList[0] || "暂无库位";
    },
    ProductForStorge() {
      this.$refs.rulesForm.validate((value) => {
        if (value) {
          if (this.selectBankList.length > 1) {
            this.$message.error("只能送检同一库位");
            return;
          }
          let wipIdList = this.selectionRows.map((item) => {
            let { wipId } = item;
            return wipId;
          });
          let params = {
            controlMode: this.inspectForm.controlType === "SN" ? 1 : 2,
            inStorageNo: this.inspectForm.inStorageNo,
            lineCode: this.topForm.lineno,
            lineName: this.topForm.lineName,
            productCode: this.form.productCode,
            productName: this.form.productName,
            stationCode: this.topForm.stationCode,
            stationName: this.topForm.stationName,
            storageLocation: this.form.storageLocation,
            storageOperatorId: 1,
            storageOperatorName: this.inspectForm.storageOperatorName,
            storageWarehouse: this.form.storageNo,
            wipIdList,
          };
          postAction(this.url.ProductForStorge, params).then((res) => {
            if (!res.success) return this.$message.warning(res.msg);
            if (res.code === 0) {
              this.SNlist();
              this.$message.success("送检成功");
              this.onClearSelected();
            }
          });
        }
      });
    },
    handleTableChange(pagination, filters, sorter) {
      this.ipagination = pagination;
      this.SNlist();
    },
    back() {
      this.$router.push("/work/productionExecution/platform");
    },
    onClearSelected() {
      this.selectedRowKeys = [];
      this.selectionRows = [];
      this.selectBankList = [];
    },
    changPro(val) {
      let item = this.Productcodes.find((item) => item.productCode === val);
      this.form.productName = item ? item.productName : "";
      this.onClearSelected();
      this.getType();
      this.getGXGD();
      this.getSCGD();
      this.getContainer();
    },
  },
};
</script>
<style lang='less'>
.product-stotage-list {
  .poros-form-item-control-wrapper {
    .poros-form-item-control {
      min-height: 32px;
      height: auto !important;
    }
  }
}
.product-execu-semifinish {
  .poros-form-item-label {
    width: 100px !important;
    text-align: right;
  }
}
</style> 